<template>
    <div class="chat-box">
        <div class="col-main">
            <div v-for="(message, index) in messages" :key="index" :class="`message ${message.sender === 'user' ? 'user-message' : 'bot-message'}`">
                {{ message.text }}
            </div>
            <div class="input-area">
                <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="请输入内容...">
                <el-button class="button" @click="sendMessage" :loading="disabledSend">发送</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue';
import { fetchEventSource } from '@microsoft/fetch-event-source';

const data = reactive({
    newMessage: '',
    messages: [
        { sender: 'admin', text: '你好今天我能帮你什么吗？', msgId: 0 },// 初始消息可以根据需要添加更多  
    ],
    disabledSend: false,
})
const { 
	messages,
	newMessage,
    disabledSend
} = toRefs(data);

function sendMessage() {
    if (data.newMessage.trim()) {
        data.disabledSend = true;
        let msglen = data.messages.length;
        let textS = '';
        data.messages.push({ sender: 'user', text: data.newMessage, msgId: msglen });
        data.messages.push({ sender: 'admin', text: '', msgId: msglen });
        let form = {
            "max_tokens": 4096,
            "top_k": 4,
            "temperature": 0.5,
            "messages": [
                {
                    "role": "user",
                    "content": data.newMessage
                }
            ],
            "model": "Pro",
            "stream": true
        }
        data.newMessage = ''; // 清空输入框
        let eventSource = fetchEventSource('https://spark-api-open.xf-yun.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                "Authorization": "Bearer MKmMGQEXdYDzmwluEWhV:ORTpoDVWWwnXRlujJwxU",
            },
            body: JSON.stringify(form),
            openWhenHidden: true,
            onopen(ops) {
                // console.log(ops);
            },
            onmessage(res) {
                // eventSource.close();
                if (res.data == '[DONE]') {
                    data.disabledSend = false;
                } else {
                    let resdata = JSON.parse(res.data);
                    textS+= resdata.choices[0].delta.content;
                    data.messages[msglen + 1] = { sender: 'admin', text: textS, msglen };
                    // console.log(data.messages)
                }
            },
            onerror(err) {
                throw Error(err);
            }
        });
        
    }
}
</script>

<style lang="less" scoped>

</style>